/**
 * pullToRefresh.js
 * 页面刷新插件
 */
;(function(window) {
    'use strict';
    var PullToRefresh = function(params, callback) {
        this.extend(this.params, params);
        this._init(callback);
    }

    var touchYDelta;
    var isLoading = false;
    var docElem = window.document.documentElement,
        loadWrapH,
        win = {
            width: window.innerWidth,
            height: window.innerHeight
        },
        winfactor = 0.2,
        translateVal,
        isMoved = false,
        firstTouchY, initialScroll;
    PullToRefresh.prototype = {
        params: {
            container: '.aui-refresh-load',
            friction: 2.5,
            triggerDistance: 200,
            callback: false,
            top: 0,
            selector: '.aui-refresh-content'

        },
        _init: function(callback) {
            var self = this;
            var loadingHtml =
                '<div class="aui-refresh-load"><div class="aui-refresh-pull-arrow"></div></div>';
            var insertDom = document.querySelector(self.params.selector)
            insertDom.insertAdjacentHTML('beforeend', loadingHtml);
            var refreshContainer = document.querySelector(self.params.selector);
            refreshContainer.addEventListener('touchstart', function(ev) {
                self.touchStart(ev)
            }, {
                passive: false
            });
            refreshContainer.addEventListener('touchmove', function(ev) {
                self.touchMove(ev)
            }, {
                passive: false
            });
            refreshContainer.addEventListener('touchend', function(ev) {
                self.touchEnd(ev, callback);
            }, {
                passive: false
            });
        },
        touchStart: function(ev) {
            var self = this;
            // document.querySelector(this.params.container).classList.remove("refreshing");
            if (isLoading) {
                return;
            }
            isMoved = false;
            var refreshContainer = document.querySelector(self.params.container);
            refreshContainer.style.webkitTransitionDuration = '0ms';
            refreshContainer.style.transitionDuration = '0ms';
            touchYDelta = '';
            var touchobj = ev.changedTouches[0];
            // register first touch "y"

            firstTouchY = parseInt(touchobj.clientY);
            initialScroll = this.scrollY();
        },

        touchMove: function(ev) {
            if (isLoading) {
                ev.preventDefault();
                return;
            }
            var self = this;
            var moving = function() {
                var touchobj = ev.changedTouches[0], // reference first touch point for this event
                    touchY = parseInt(touchobj.clientY);
                touchYDelta = touchY - firstTouchY;
                if (self.scrollY() === 0 && touchYDelta > 0) {
                    ev.preventDefault();
                }
                if (initialScroll > 0 || self.scrollY() > 0 || self.scrollY() === 0 && touchYDelta < 0) {
                    firstTouchY = touchY;
                    return;
                }
                translateVal = Math.pow(touchYDelta, 0.85);
                var refreshContainer = document.querySelector(self.params.container);
                refreshContainer.style.webkitTransform = refreshContainer.style.transform =
                    'translate3d(0, ' + translateVal + 'px, 0)';
                isMoved = true;
                if (touchYDelta > self.params.triggerDistance) {
                    refreshContainer.classList.add("aui-refresh-pull-up");
                    refreshContainer.classList.remove("aui-refresh-pull-down");
                } else {
                    refreshContainer.classList.add("aui-refresh-pull-down");
                    refreshContainer.classList.remove("aui-refresh-pull-up");
                }
            };
            this.throttle(moving(), 20);
        },
        touchEnd: function(ev, callback) {
            var self = this;
            var refreshContainer = document.querySelector(self.params.container);
            if (isLoading || !isMoved) {
                isMoved = false;
                return;
            }
            // 根据下拉高度判断是否加载
            if (touchYDelta >= this.params.triggerDistance) {
                isLoading = true; //正在加载中
                ev.preventDefault();
                refreshContainer.style.webkitTransitionDuration =
                    refreshContainer.style.transitionDuration = '300ms';
                refreshContainer.style.webkitTransform =
                    refreshContainer.style.transform = 'translate3d(0,70px,0)';
                document.querySelector(".aui-refresh-pull-arrow").style.webkitTransitionDuration =
                    document.querySelector(".aui-refresh-pull-arrow").style.transitionDuration = '0ms';
                refreshContainer.classList.add("aui-refreshing");
                callback({
                    status: "success"
                });

            } else {

                refreshContainer.style.webkitTransitionDuration =
                refreshContainer.style.transitionDuration = '300ms';
                refreshContainer.style.webkitTransform =
                refreshContainer.style.transform = 'translate3d(0,0,0)';
                callback({
                    status: "fail"
                });

            }
            isMoved = false;
            return;
        },
        cancelLoading: function() {
            var self = this;
            isLoading = false;
            var refreshContainer = document.querySelector(self.params.container);
            refreshContainer.classList.remove("aui-refreshing");
            refreshContainer.style.webkitTransitionDuration =
                refreshContainer.style.transitionDuration = '300ms';
            refreshContainer.style.webkitTransitionDuration =
                refreshContainer.style.transitionDuration = '0ms';
            refreshContainer.style.webkitTransform =
                refreshContainer.style.transform = 'translate3d(0,0,0)';
            refreshContainer.classList.remove("aui-refresh-pull-up");
            refreshContainer.classList.add("aui-refresh-pull-down");
            return;
        },
        scrollY: function() {
            return window.pageYOffset || docElem.scrollTop;
        },
        throttle: function(fn, delay) {
            var allowSample = true;
            return function(e) {
                if (allowSample) {
                    allowSample = false;
                    setTimeout(function() {
                        allowSample = true;
                    }, delay);
                    fn(e);
                }
            };
        },
        winresize: function() {
            var resize = function() {
                win = {
                    width: window.innerWidth,
                    height: window.innerHeight
                };
            };
            throttle(resize(), 10);
        },
        extend: function(a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }
    }
    window.PullToRefresh = PullToRefresh;
})(window);

function downPullRefresh(selector)
{   var _selector = (typeof arguments[0] == "undefined" || arguments[0] == null) ? '.aui-refresh-content' : arguments[0];
    // var _top = (typeof arguments[1] == "undefined" || arguments[1] == null) ? 0 : arguments[1];
    var PullRefresh = new PullToRefresh({
        triggerDistance: 100,
        selector:_selector
    }, function(ret) {
        if (ret.status == 'success') {
            setTimeout(function() {
                PullRefresh.cancelLoading(); //刷新成功后调用此方法隐藏
                window.location.reload();
            }, 1500)
        }
    });
}
